"""
认证相关API路由
"""
from datetime import timedelta, datetime
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordRequestForm
from motor.motor_asyncio import AsyncIOMotorDatabase
import redis.asyncio as redis

from app.core.config import settings
from app.core.security import (
    verify_password, 
    get_password_hash, 
    create_access_token, 
    create_refresh_token,
    generate_password_reset_token,
    verify_password_reset_token,
    verify_token
)
from app.core.response import success_response, error_response, ApiResponse
from app.api.deps import get_db, get_redis_client, get_current_user
from bson import ObjectId

from app.models.user import (
    UserCreate, 
    UserLogin, 
    User, 
    UserResponse, 
    Token, 
    ForgotPassword, 
    ResetPassword,
    ChangePassword,
    RefreshTokenRequest
)

from app.core.permissions import get_permissions_for_role
from app.services.role_service import RoleService

router = APIRouter()

@router.get("/check-username", response_model=ApiResponse, summary="检查用户名是否可用")
async def check_username(
    username: str,
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    检查用户名是否可用
    """
    # 检查用户名是否已存在
    existing_user = await db.users.find_one({"username": username})
    available = existing_user is None
    
    return success_response(data={"available": available})

@router.get("/check-email", response_model=ApiResponse, summary="检查邮箱是否可用")
async def check_email(
    email: str,
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    检查邮箱是否可用
    """
    # 检查邮箱是否已存在
    existing_user = await db.users.find_one({"email": email})
    available = existing_user is None
    
    return success_response(data={"available": available})

@router.post("/register", response_model=ApiResponse, summary="注册新用户")
async def register(
    user_in: UserCreate,
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    注册新用户
    """
    # 检查邮箱是否已存在
    existing_user = await db.users.find_one({"email": user_in.email})
    if existing_user:
        return error_response(
            error_type="VALIDATION_ERROR",
            message="邮箱已被注册",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 生成密码哈希
    hashed_password = get_password_hash(user_in.password)
    
    # 获取角色对应的权限
    permissions = []
    for role_id in user_in.system_roles:
        try:
            role = await RoleService.get_role_with_permissions(db, role_id)
            if role:
                permissions.extend(p for p in role.get("permissions", []) if p not in permissions)
        except Exception:
            continue
    
    # 创建用户文档
    user_doc = user_in.model_dump(exclude={"password"})
    user_doc.update({
        "hashed_password": hashed_password,
        "permissions": permissions,
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow()
    })
    
    # 插入数据库
    result = await db.users.insert_one(user_doc)
    
    # 获取创建的用户
    created_user = await db.users.find_one({"_id": result.inserted_id})
    
    # 构建用户响应数据
    user_response = {
        "id": str(created_user["_id"]),
        "name": created_user["name"],
        "email": created_user["email"],
        "department_id": created_user.get("department_id"),
        "position": created_user.get("position"),
        "phone": created_user.get("phone"),
        "avatar": created_user.get("avatar"),
        "status": created_user.get("status", "pending"),
        "is_verified": created_user.get("is_verified", False),
        "system_roles": created_user.get("system_roles", []),
        "roles": await RoleService.get_role_codes_by_ids(db, created_user.get("system_roles", [])),
        "permissions": created_user["permissions"],
        "created_at": created_user.get("created_at"),
        "updated_at": created_user.get("updated_at"),
        "last_login": created_user.get("last_login")
    }
    
    return success_response(data=user_response, message="用户注册成功")

@router.options("/login", status_code=200)
async def login_options():
    """处理登录端点的OPTIONS预检请求"""
    from fastapi.responses import Response
    response = Response(status_code=200)
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "POST, OPTIONS"
    response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
    response.headers["Access-Control-Max-Age"] = "86400"
    return response

@router.post("/login", response_model=ApiResponse, summary="用户登录获取令牌")
async def login(
    login_data: UserLogin,
    request: Request,
    db: AsyncIOMotorDatabase = Depends(get_db),
    redis_client: Optional[redis.Redis] = Depends(get_redis_client)
) -> Any:
    """
    获取访问令牌
    """
    import logging
    from app.utils.activity_logger import ActivityLogger, ActionTypes
    
    logger = logging.getLogger(__name__)
    
    # 获取客户端信息
    ip_address = request.client.host if request.client else None
    user_agent = request.headers.get("user-agent", "")
    
    logger.info(f"Login attempt for username: {login_data.username} from IP: {ip_address}")
    
    # 1. 基本输入验证
    if not login_data.username or not login_data.password:
        logger.warning(f"Empty username or password for login attempt")
        return error_response(
            error_type="VALIDATION_ERROR",
            message="用户名和密码不能为空",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 2. 输入清理和验证
    sanitized_username = login_data.username.strip()
    sanitized_password = login_data.password
    
    # 验证密码长度(bcrypt限制为72字节)
    password_bytes = sanitized_password.encode('utf-8')
    if len(password_bytes) > 72:
        logger.warning(f"Password too long for user: {sanitized_username}")
        return error_response(
            error_type="VALIDATION_ERROR",
            message="密码长度超过限制,请使用较短的密码",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 验证用户名长度
    if len(sanitized_username) < 2 or len(sanitized_username) > 50:
        logger.warning(f"Invalid username length: {len(sanitized_username)}")
        return error_response(
            error_type="VALIDATION_ERROR",
            message="用户名长度不符合要求",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 3. 查找用户 - 支持用户名、姓名或邮箱登录
    logger.info(f"Searching for user with identifier: {sanitized_username}")
    user = await db.users.find_one({
        "$or": [
            {"username": sanitized_username},
            {"name": sanitized_username},
            {"email": sanitized_username}
        ]
    })
    
    if not user:
        logger.warning(f"User not found: {sanitized_username}")
        await ActivityLogger.log_login(
            db=db,
            user_id="unknown",
            ip_address=ip_address,
            user_agent=user_agent,
            success=False
        )
        return error_response(
            error_type="AUTHENTICATION_ERROR",
            message="用户名或密码错误，请检查后重试",
            code=status.HTTP_401_UNAUTHORIZED
        )
    
    user_id = str(user["_id"])
    logger.info(f"User found: {user.get('name')} ({user.get('email')}) ID: {user_id}")
    
    logger.info(f"User found: {user.get('name')} ({user.get('email')})")
    
    # 检查账户状态
    if user.get("status") == "inactive":
        logger.warning(f"Account disabled for user: {login_data.username}")
        await ActivityLogger.log_login(
            db=db,
            user_id=str(user["_id"]),
            ip_address=ip_address,
            user_agent=user_agent,
            success=False
        )
        return error_response(
            error_type="AUTHENTICATION_ERROR",
            message="账户已被禁用，请联系管理员",
            code=status.HTTP_401_UNAUTHORIZED
        )
    
    # 检查账户验证状态 - 暂时注释掉邮箱验证逻辑
    # if not user.get("is_verified", False):
    #     logger.warning(f"Account not verified for user: {login_data.username}")
    #     await ActivityLogger.log_login(
    #         db=db,
    #         user_id=str(user["_id"]),
    #         ip_address=ip_address,
    #         user_agent=user_agent,
    #         success=False
    #     )
    #     return error_response(
    #         error_type="AUTHENTICATION_ERROR",
    #         message="账户尚未验证，请先验证邮箱",
    #         code=status.HTTP_401_UNAUTHORIZED
    #     )
    
    # 5. 验证密码
    password_valid = verify_password(sanitized_password, user["hashed_password"])
    logger.info(f"Password verification result for user {user_id}: {password_valid}")
    
    if not password_valid:
        logger.warning(f"Password verification failed for user: {sanitized_username} (ID: {user_id})")
        await ActivityLogger.log_login(
            db=db,
            user_id=user_id,
            ip_address=ip_address,
            user_agent=user_agent,
            success=False
        )
        return error_response(
            error_type="AUTHENTICATION_ERROR",
            message="用户名或密码错误，请检查后重试",
            code=status.HTTP_401_UNAUTHORIZED
        )
    
    # 创建访问令牌
    access_token_expires = timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
    token_data = {
        "user_id": str(user["_id"]),
        "email": user["email"],
        "roles": user.get("system_roles", []),
        "permissions": user["permissions"]
    }
    
    access_token = create_access_token(
        data=token_data,
        expires_delta=access_token_expires
    )
    
    refresh_token = create_refresh_token(data=token_data)
    
    # 6. 登录成功处理
    current_time = datetime.utcnow()
    
    # 清除登录失败记录
    if redis_client:
        try:
            fail_key = f"login_fail:{user_id}"
            await redis_client.delete(fail_key)
            logger.info(f"Cleared login failure count for user {user_id}")
        except Exception as e:
            logger.error(f"Failed to clear login failure count: {str(e)}")
    
    # 更新用户登录信息
    await db.users.update_one(
        {"_id": user["_id"]},
        {
            "$set": {"last_login": current_time},
            "$inc": {"login_count": 1}
        }
    )
    
    # 记录成功的登录
    await ActivityLogger.log_login(
        db=db,
        user_id=user_id,
        ip_address=ip_address,
        user_agent=user_agent,
        success=True
    )
    
    # 记录登录活动
    await ActivityLogger.log_user_action(
        db=db,
        user_id=user_id,
        action=ActionTypes.USER_LOGIN,
        description=f"用户 {user['name']} 登录系统",
        ip_address=ip_address,
        user_agent=user_agent
    )
    
    # 存储刷新令牌到Redis（如果Redis可用）
    if redis_client:
        refresh_token_key = f"refresh_token:{user_id}"
        await redis_client.set(
            refresh_token_key,
            refresh_token,
            ex=settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60
        )
    
    # 处理 system_roles：将 ObjectId 转换为字符串
    system_roles = user.get("system_roles", [])
    system_roles_str = [
        str(role_id) if isinstance(role_id, ObjectId) else role_id 
        for role_id in system_roles
    ] if system_roles else []
    
    # 处理 department_id：将 ObjectId 转换为字符串
    department_id = user.get("department_id")
    department_id_str = str(department_id) if isinstance(department_id, ObjectId) else department_id
    
    # 构建用户响应数据
    user_response = {
        "id": user_id,
        "username": user.get("username", ""),
        "name": user["name"],
        "email": user["email"],
        "department_id": department_id_str,
        "position": user.get("position"),
        "phone": user.get("phone"),
        "avatar": user.get("avatar"),
        "status": user.get("status", "pending"),
        "is_verified": user.get("is_verified", False),
        "system_roles": system_roles_str,
        "roles": await RoleService.get_role_codes_by_ids(db, system_roles_str),
        "permissions": user["permissions"],
        "created_at": user.get("created_at", current_time),
        "updated_at": user.get("updated_at", current_time),
        "last_login": current_time
    }
    
    # 构建登录响应数据
    login_data = {
        "access_token": access_token,
        "token_type": "bearer",
        "expires_in": settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 60,
        "user": user_response
    }
    
    return success_response(data=login_data, message="登录成功")

@router.post("/refresh-token", response_model=ApiResponse, summary="使用刷新令牌获取新令牌")
async def refresh_token(
    refresh_request: RefreshTokenRequest,
    db: AsyncIOMotorDatabase = Depends(get_db),
    redis_client: Optional[redis.Redis] = Depends(get_redis_client)
) -> Any:
    """
    使用刷新令牌获取新的访问令牌和刷新令牌
    实现refresh token轮换机制以提高安全性
    """
    import logging
    logger = logging.getLogger(__name__)
    
    try:
        refresh_token = refresh_request.refresh_token if refresh_request else None
        logger.info(f"开始刷新token，refresh_token预览: {refresh_token[:20] if refresh_token else 'None'}...")
        
        if not refresh_token:
            logger.warning("未提供refresh token")
            return error_response(
                error_type="AUTHENTICATION_ERROR",
                message="缺少刷新令牌",
                code=status.HTTP_401_UNAUTHORIZED
            )
        
        # 验证刷新令牌
        payload = verify_token(refresh_token, token_type="refresh")
        user_id = payload.get("user_id")
        
        if not user_id:
            logger.warning("刷新令牌中缺少user_id")
            return error_response(
                error_type="AUTHENTICATION_ERROR",
                message="无效的刷新令牌格式",
                code=status.HTTP_401_UNAUTHORIZED
            )
        
        # 检查Redis中的刷新令牌（如果Redis可用）
        if redis_client:
            try:
                stored_token = await redis_client.get(f"refresh_token:{user_id}")
                if not stored_token:
                    logger.warning(f"Redis中未找到用户 {user_id} 的刷新令牌")
                    return error_response(
                        error_type="AUTHENTICATION_ERROR",
                        message="刷新令牌已失效",
                        code=status.HTTP_401_UNAUTHORIZED
                    )
                
                if stored_token.decode() != refresh_token:
                    logger.warning(f"用户 {user_id} 的刷新令牌不匹配")
                    return error_response(
                        error_type="AUTHENTICATION_ERROR",
                        message="无效的刷新令牌",
                        code=status.HTTP_401_UNAUTHORIZED
                    )
                
                # 将旧的refresh token加入黑名单
                await redis_client.setex(
                    f"blacklist_refresh:{refresh_token}",
                    settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,  # 与refresh token相同的过期时间
                    "revoked"
                )
                logger.info(f"已将旧的refresh token加入黑名单")
                
            except Exception as e:
                logger.error(f"Redis操作失败: {str(e)}")
                # Redis失败时继续处理，但记录警告
        
        # 获取用户信息
        try:
            user_object_id = ObjectId(user_id)
        except Exception:
            logger.warning(f"无效的用户ID格式: {user_id}")
            return error_response(
                error_type="AUTHENTICATION_ERROR",
                message="无效的刷新令牌",
                code=status.HTTP_401_UNAUTHORIZED
            )
        
        user = await db.users.find_one({"_id": user_object_id})
        if not user:
            logger.warning(f"用户 {user_id} 不存在")
            return error_response(
                error_type="NOT_FOUND_ERROR",
                message="用户不存在",
                code=status.HTTP_404_NOT_FOUND
            )
        
        # 检查用户状态
        if user.get("status") != "active":
            logger.warning(f"用户 {user_id} 状态不是active: {user.get('status')}")
            return error_response(
                error_type="AUTHENTICATION_ERROR",
                message="用户账户已被禁用",
                code=status.HTTP_401_UNAUTHORIZED
            )
        
        # 创建新的访问令牌和刷新令牌
        access_token_expires = timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
        token_data = {
            "user_id": str(user["_id"]),
            "email": user["email"],
            "roles": user.get("system_roles", []),
            "permissions": user["permissions"]
        }
        
        access_token = create_access_token(
            data=token_data,
            expires_delta=access_token_expires
        )
        
        # 创建新的刷新令牌（token轮换）
        new_refresh_token = create_refresh_token(data=token_data)
        
        # 将新的刷新令牌存储到Redis（如果可用）
        if redis_client:
            try:
                await redis_client.setex(
                    f"refresh_token:{user_id}",
                    settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,
                    new_refresh_token
                )
                logger.info(f"新的refresh token已存储到Redis")
            except Exception as e:
                logger.error(f"存储新refresh token到Redis失败: {str(e)}")
        
        # 更新用户最后登录时间
        current_time = datetime.utcnow()
        await db.users.update_one(
            {"_id": user_object_id},
            {"$set": {"last_login": current_time}}
        )
        
        # 构建用户响应数据
        user_response = {
            "id": str(user["_id"]),
            "username": user.get("username", ""),
            "name": user["name"],
            "email": user["email"],
            "department_id": user.get("department_id"),
            "position": user.get("position"),
            "phone": user.get("phone"),
            "avatar": user.get("avatar"),
            "status": user["status"],
            "is_verified": user["is_verified"],
            "system_roles": user.get("system_roles", []),
            "permissions": user["permissions"],
            "created_at": user["created_at"],
            "updated_at": user["updated_at"],
            "last_login": current_time
        }
        
        # 构建刷新令牌响应数据
        refresh_data = {
            "access_token": access_token,
            "refresh_token": new_refresh_token,  # 返回新的refresh token
            "token_type": "bearer",
            "expires_in": settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 60,
            "user": user_response
        }
        
        logger.info(f"用户 {user_id} token刷新成功")
        return success_response(data=refresh_data, message="令牌刷新成功")
    
    except HTTPException as e:
        logger.error(f"HTTP异常: {str(e)}")
        raise
    except Exception as e:
        logger.error(f"刷新token时发生未知错误: {str(e)}")
        return error_response(
            error_type="AUTHENTICATION_ERROR",
            message="无法验证凭据",
            code=status.HTTP_401_UNAUTHORIZED
        )

@router.post("/logout", response_model=ApiResponse, summary="用户登出")
async def logout(
    request: Request,
    current_user: dict = Depends(get_current_user),
    redis_client: Optional[redis.Redis] = Depends(get_redis_client),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    用户登出
    """
    from app.utils.activity_logger import ActivityLogger, ActionTypes
    
    # 获取客户端信息
    ip_address = request.client.host if request.client else None
    user_agent = request.headers.get("user-agent", "")
    
    # 删除Redis中的刷新令牌（如果Redis可用）
    user_id = current_user.get("user_id")
    if redis_client and user_id:
        try:
            await redis_client.delete(f"refresh_token:{user_id}")
        except Exception as e:
            # Redis操作失败不影响登出
            pass
    
    # 记录登出活动
    await ActivityLogger.log_user_action(
        db=db,
        user_id=user_id,
        action=ActionTypes.USER_LOGOUT,
        description=f"用户 {current_user.get('name', 'Unknown')} 登出系统",
        ip_address=ip_address,
        user_agent=user_agent
    )
    
    return success_response(message="登出成功")

@router.post("/forgot-password", response_model=ApiResponse, summary="请求密码重置")
async def forgot_password(
    forgot_password_in: ForgotPassword,
    request: Request,
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    请求密码重置
    """
    from app.utils.email_sender import EmailSender
    
    # 查找用户
    user = await db.users.find_one({"email": forgot_password_in.email})
    if not user:
        # 为了安全，即使用户不存在也返回成功
        return success_response(message="如果邮箱存在，密码重置邮件已发送")
    
    # 生成密码重置令牌
    reset_token = generate_password_reset_token(forgot_password_in.email)
    
    # 构建重置链接
    base_url = str(request.base_url).rstrip('/')
    reset_url = f"{base_url}/reset-password?token={reset_token}"
    
    # 发送密码重置邮件
    email_sent = await EmailSender.send_email(
        db=db,
        to_email=forgot_password_in.email,
        subject="密码重置请求",
        content=f"""
您好 {user.get('name', '用户')}，

您请求重置密码。请点击以下链接重置您的密码：

{reset_url}

此链接将在24小时内有效。

如果您没有请求重置密码，请忽略此邮件。

此邮件由系统自动发送，请勿回复。
        """,
        html_content=f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
        .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
        .header {{ background-color: #409EFF; color: white; padding: 20px; text-align: center; }}
        .content {{ padding: 20px; background-color: #f9f9f9; }}
        .button {{ display: inline-block; padding: 12px 24px; background-color: #409EFF; color: white; text-decoration: none; border-radius: 4px; margin: 20px 0; }}
        .footer {{ text-align: center; padding: 20px; color: #999; font-size: 12px; }}
        .warning {{ color: #E6A23C; font-size: 14px; margin-top: 20px; }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>密码重置请求</h2>
        </div>
        <div class="content">
            <p>您好 <strong>{user.get('name', '用户')}</strong>，</p>
            <p>您请求重置密码。请点击以下按钮重置您的密码：</p>
            <div style="text-align: center;">
                <a href="{reset_url}" class="button">重置密码</a>
            </div>
            <p>或者复制以下链接到浏览器中打开：</p>
            <p style="word-break: break-all; color: #666;">{reset_url}</p>
            <p class="warning">⚠️ 此链接将在24小时内有效。如果您没有请求重置密码，请忽略此邮件。</p>
        </div>
        <div class="footer">
            <p>此邮件由系统自动发送，请勿回复。</p>
        </div>
    </div>
</body>
</html>
        """
    )
    
    if not email_sent:
        # 如果邮件发送失败，记录日志但不暴露给用户（安全考虑）
        import logging
        logger = logging.getLogger(__name__)
        logger.warning(f"密码重置邮件发送失败: {forgot_password_in.email}")
    
    return success_response(message="如果邮箱存在，密码重置邮件已发送")

@router.post("/reset-password", response_model=ApiResponse, summary="重置密码")
async def reset_password(
    reset_password_in: ResetPassword,
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    重置密码
    """
    # 验证密码重置令牌
    email = verify_password_reset_token(reset_password_in.token)
    if not email:
        return error_response(
            error_type="VALIDATION_ERROR",
            message="无效或过期的令牌",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 检查密码确认
    if reset_password_in.password != reset_password_in.confirm_password:
        return error_response(
            error_type="VALIDATION_ERROR",
            message="密码不匹配",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 查找用户
    user = await db.users.find_one({"email": email})
    if not user:
        return error_response(
            error_type="NOT_FOUND_ERROR",
            message="用户不存在",
            code=status.HTTP_404_NOT_FOUND
        )
    
    # 更新密码
    hashed_password = get_password_hash(reset_password_in.password)
    await db.users.update_one(
        {"_id": user["_id"]},
        {"$set": {"hashed_password": hashed_password}}
    )
    
    return success_response(message="密码重置成功")

@router.post("/change-password", response_model=ApiResponse, summary="修改密码")
async def change_password(
    change_password_in: ChangePassword,
    request: Request,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    修改密码
    """
    from app.utils.activity_logger import ActivityLogger, ActionTypes
    
    # 获取客户端信息
    ip_address = request.client.host if request.client else None
    user_agent = request.headers.get("user-agent", "")
    
    # 检查密码确认
    if change_password_in.new_password != change_password_in.confirm_password:
        return error_response(
            error_type="VALIDATION_ERROR",
            message="密码不匹配",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 获取用户
    user = await db.users.find_one({"_id": current_user.get("user_id")})
    if not user:
        return error_response(
            error_type="NOT_FOUND_ERROR",
            message="用户不存在",
            code=status.HTTP_404_NOT_FOUND
        )
    
    # 验证旧密码
    if not verify_password(change_password_in.old_password, user["hashed_password"]):
        return error_response(
            error_type="VALIDATION_ERROR",
            message="旧密码错误",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 更新密码
    hashed_password = get_password_hash(change_password_in.new_password)
    await db.users.update_one(
        {"_id": user["_id"]},
        {"$set": {"hashed_password": hashed_password, "updated_at": datetime.utcnow()}}
    )
    
    # 记录密码修改活动
    await ActivityLogger.log_user_action(
        db=db,
        user_id=str(user["_id"]),
        action=ActionTypes.USER_CHANGE_PASSWORD,
        description=f"用户 {user['name']} 修改了密码",
        ip_address=ip_address,
        user_agent=user_agent
    )
    
    return success_response(message="密码修改成功")

@router.get("/me", response_model=ApiResponse, summary="获取当前用户信息")
async def get_me(
    current_user: dict = Depends(get_current_user)
) -> Any:
    """
    获取当前用户信息
    """
    # 构建用户响应数据
    user_response = {
        "id": current_user["user_id"],
        "username": current_user.get("username", ""),
        "name": current_user["name"],
        "email": current_user["email"],
        "department_id": current_user.get("department_id"),
        "position": current_user.get("position"),
        "phone": current_user.get("phone"),
        "avatar": current_user.get("avatar"),
        "status": current_user.get("status", "active"),
        "is_verified": current_user.get("is_verified", True),
        "system_roles": current_user.get("system_roles", []),
        "roles": current_user.get("roles", []),
        "permissions": current_user["permissions"],
        "created_at": current_user.get("created_at"),
        "updated_at": current_user.get("updated_at"),
        "last_login": current_user.get("last_login"),
        "login_count": current_user.get("login_count", 0)
    }
    
    return success_response(data=user_response, message="获取用户信息成功")
